const { FileFolder, Sheet, User, Message } = require('../model')

exports.createMessage = async (req, res, next) => {
    try {
        const { sendUser, receptionUser, content, type } = req.body
        let message = null
        const messageModel = await Message.findOne({ sendUser, receptionUser, content, type })
        if (messageModel) {
            messageModel.status = 0
            messageModel.createdAt = new Date()
            await messageModel.save()
        } else {
            let sendUserMessage = await User.findById(sendUser)
            let receptionUserMessage = await User.findById(receptionUser)
            message = new Message({ ...req.body, sendUserMessage, receptionUserMessage })
            await message.save();
        }
        res.status(200).json(
            {
                code: 200,
                data: message,
                msg: '成功'
            }
        )
    } catch (err) {
        console.log(err);

        next(err);
    }
};
exports.list = async (req, res, next) => {
    try {
        const messages = await Message.find({ receptionUser: req.query.id }).sort({ createdAt: -1 })
        res.status(200).json(
            {
                code: 200,
                data: messages,
                msg: '成功'
            }
        )
    } catch (err) {
        console.log(err);

        next(err);
    }
}
exports.readMessage = async (req, res, next) => {
    try {
        const message = await Message.findByIdAndUpdate(req.body.id, { status: req.body.status }, { new: true })
        res.status(200).json(
            {
                code: 200,
                data: message,
                msg: '成功'
            }
        )
    } catch (err) {
        next(err);
    }
}